package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    public static final String APP_INFO_ARTICLE = "app_info_article";

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (userSearchDto.getFromIndex() == 0) {
            if(user !=null){
                userSearchDto.setEntryId(user.getId());
            }
            // 异步调用保存用户输入关键词记录
            apUserSearchService.insert( userSearchDto);
        }
        //构建查询执行查询
        SearchRequest searchRequest = getSearchRequest(userSearchDto, searchWords);

        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            List<SearchArticleVo> resultList = getSearchArticleVos(searchResponse);
            return ResponseResult.okResult(resultList);
        }catch (IOException e){
            e.printStackTrace();
            log.error("search result error:{}",e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }


    /**
     * 解析响应结果,拼接高亮显示
     * @param searchResponse
     * @return
     */
    private List<SearchArticleVo> getSearchArticleVos(SearchResponse searchResponse) {
        SearchHits searchHits = searchResponse.getHits();
        List<SearchArticleVo> resultList = new ArrayList<>();

        //总记录数
        long total = searchHits.getTotalHits().value;
        log.info("search result total:{}",total);

        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String jsonString = hit.getSourceAsString();
            SearchArticleVo apArticle = JSON.parseObject(jsonString, SearchArticleVo.class);

            // 获取高亮结果集
            Text[] titles = hit.getHighlightFields().get("title").getFragments();

            // 保留原始标题
            String title = StringUtils.join(titles);
            if (StringUtils.isNotBlank(title)) {
                apArticle.setTitle(title);
            }

            // 拼接静态页全路径
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
            resultList.add(apArticle);
        }
        return resultList;
    }

    /**
     * 封装请求对象
     * @param userSearchDto
     * @param searchWords
     * @return
     */
    private SearchRequest getSearchRequest(UserSearchDto userSearchDto, String searchWords) {
        SearchRequest searchRequest = new SearchRequest(APP_INFO_ARTICLE);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建查询条件和过滤等
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        //关键字查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", searchWords);
        queryBuilder.must(matchQueryBuilder);
        //范围查询
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime")
                .lt(userSearchDto.getMinBehotTime().getTime());
        queryBuilder.filter(rangeQueryBuilder);

        //分页
        sourceBuilder.from(0);
        sourceBuilder.size(userSearchDto.getPageSize());
        //排序，按发布时间倒序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);

        //装载
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        return searchRequest;
    }

    @Override
    public void saveArticle(SearchArticleVo article) {
        IndexRequest request = new IndexRequest("app_info_article");
        request.id(String.valueOf(article.getId()));
        request.source(JSON.toJSONString(article), XContentType.JSON);
        try {
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章数据失败: {}",article);
        }
    }

    @Override
    public void deleteArticle(Long articleId) {
        DeleteRequest request = new DeleteRequest("app_info_article",String.valueOf(articleId));
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章数据失败: {}",e.getMessage());
        }
    }
}